package cn.edu.zafu.bigdata.mahuilin;

import java.io.*;
import java.util.Scanner;

public class FileOperation {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要保存的文本：");
        String inputText = scanner.nextLine();
        String studentId = "2022010101"; // 假设学号是2022010101，可以根据需要修改
        writeToFile("files/" + studentId + ".txt", inputText);
        String content = readFromFile("files/" + studentId + ".txt");
        System.out.println("文件内容如下：");
        System.out.println(content);
        scanner.close();
    }

    public static void writeToFile(String fileName, String content) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File(fileName)))) {
            writer.write(content);
        } catch (IOException e) {
            System.err.println("写入文件时发生错误：" + e.getMessage());
        }
    }

    public static String readFromFile(String fileName) {
        StringBuilder contentBuilder = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)))) {
            String line;
            while ((line = reader.readLine()) != null) {
                contentBuilder.append(line).append("\n");
            }
        } catch (IOException e) {
            System.err.println("读取文件时发生错误：" + e.getMessage());
            return "";
        }
        return contentBuilder.toString();
    }
}